package com.zhihaoliang.baseframe.ui;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.AsyncDifferConfig;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.zhihaoliang.baseframe.R;
import com.zhihaoliang.baseframe.databinding.CommentItemBinding;
import com.zhihaoliang.baseframe.db.entity.CommentEntity;

/**
 * 创建日期：2020-03-01
 * 描述:
 * 作者:支豪亮
 */
public class CommentAdapter extends ListAdapter<CommentEntity, CommentAdapter.CommentViewHolder> {

    private final CommentClickCallback mCommentClickCallback;

    protected CommentAdapter(@NonNull CommentClickCallback commentClickCallback) {
        super(new AsyncDifferConfig.Builder<>(new DiffUtil.ItemCallback<CommentEntity>() {

            @Override
            public boolean areItemsTheSame(@NonNull CommentEntity oldItem, @NonNull CommentEntity newItem) {
                return oldItem.getId() == newItem.getId();
            }

            @Override
            public boolean areContentsTheSame(@NonNull CommentEntity oldItem, @NonNull CommentEntity newItem) {
                return oldItem.getId() == newItem.getId() &&
                        oldItem.getPostAt().equals(newItem.getPostAt()) &&
                        oldItem.getProductId() == newItem.getProductId() &&
                        TextUtils.equals(oldItem.text(), newItem.text());
            }
        }).build());
        mCommentClickCallback = commentClickCallback;

    }

    @NonNull
    @Override
    public CommentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        CommentItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.product_item, parent, false);
        binding.setCallback(mCommentClickCallback);
        return new CommentViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull CommentViewHolder holder, int position) {
        holder.mBinding.setComment(getItem(position));
        holder.mBinding.executePendingBindings();
    }

    static class CommentViewHolder extends RecyclerView.ViewHolder {

        final CommentItemBinding mBinding;

        public CommentViewHolder(CommentItemBinding commentItemBinding) {
            super(commentItemBinding.getRoot());
            mBinding = commentItemBinding;
        }
    }
}
